/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package downloadmanager.component;

import downloadmanager.event.XEvent;
import downloadmanager.event.XEventListener;
import java.util.ArrayList;
import java.util.List;
import util.StringExtensions;

/**
 *
 * @author Administrator
 */
public class ProgressSegmentList {

    private double min = 0;
    private double max = 0;
    private List<ProgressSegment> segments;
    public final XEvent<Object> ValueChange = new XEvent<Object>();
    private XEventListener<Object> onSegmentValueChange;

    public ProgressSegmentList() {
        segments = new ArrayList<ProgressSegment>();
        final ProgressSegmentList self = this;
        onSegmentValueChange = new XEventListener<Object>() {

            public void eventFired(Object sender, Object args) {
                ValueChange.fire(self, null);
            }
        };
    }

    public List<ProgressSegment> getSegments() {
        return segments;
    }

    private void internalAddSegment(ProgressSegment segment) {
        segments.add(segment);
        segment.ValueChange.subscribe(onSegmentValueChange);
    }

    public void addProgressSegment(ProgressSegment segment) {
        internalAddSegment(segment);
        ValueChange.fire(this, null);
    }

    public void addProgressSegments(ProgressSegment[] segments) {
        for (ProgressSegment segment : segments) {
            internalAddSegment(segment);
        }
        ValueChange.fire(this, null);
    }

    public void internalRemoveSegment(ProgressSegment segment) {
        segment.ValueChange.unsubscribe(onSegmentValueChange);
        segments.remove(segment);
    }

    public void removeSegment(ProgressSegment segment) {
        internalRemoveSegment(segment);
        ValueChange.fire(this, null);
    }

    /**
     * Remove all segments from display
     */
    public void clearSegments() {
        while (segments.size() != 0) {
            internalRemoveSegment(segments.get(0));
        }
        ValueChange.fire(this, null);
    }

    public double getMin() {
        return this.min;
    }

    public void setMin(double min) {
        this.min = min;
        ValueChange.fire(this, null);
    }

    public double getMax() {
        return this.max;
    }

    public void setMax(double max) {
        this.max = max;
        ValueChange.fire(this, null);
    }

    @Override
    public String toString() {
        return StringExtensions.join(new String[]{String.valueOf(min), StringExtensions.join(segments, " "), String.valueOf(max)}, "-");
    }
}
